package com.sdy.healthcode.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.healthcode.biz.dto.PersonInfoVo;
import com.sdy.healthcode.biz.dto.ThisCourtVO;
import com.sdy.healthcode.biz.mapper.UserMapper;
import com.sdy.healthcode.biz.model.User;
import com.sdy.healthcode.biz.param.PersonnelIdParam;
import com.sdy.healthcode.biz.param.UpdatePersonnelParam;
import com.sdy.healthcode.biz.service.UserService;
import com.sdy.healthcode.biz.utils.CopyUtil;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2020-02-18
 */
@Slf4j
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserByPhone(String phone) {
        return lambdaQuery().eq(User::getPhone, phone).one();
    }

    @Override
    public User getUserByWxid(String wxid) {
        return lambdaQuery().eq(User::getWxid, wxid).one();
    }

    @Override
    public void updateUserWxid(Integer userId, String wxid) {
        lambdaUpdate().eq(User::getWxid, wxid).ne(User::getId, userId).set(User::getWxid, null).update();
        lambdaUpdate().eq(User::getId, userId).set(User::getWxid, wxid).update();
    }

    @Override
    public User createUser(String phone, String wxid) {
        User user = new User()
                .setPhone(phone)
                .setAuthScan(0)
                .setAuthManage(0)
                .setType(1)
                .setWxid(wxid)
                .setCreateTime(new Date())
                .setAddrLocal("");
        save(user);
        return user;
    }

    @Override
    public User xGetOrCreateUserByPhone(String phone, String wxid) {
        User user = getUserByPhone(phone);
        if (user == null) {
            user = createUser(phone, wxid);
        } else if (StringUtil.isNotBlank(wxid)) {
            updateUserWxid(user.getId(), wxid);
        }
        return user;
    }

    @Override
    public User xGetOrCreateUserByWxid(String wxid) {
        User user = getUserByWxid(wxid);
        if (user == null) {
            user = createUser(null, wxid);
        }
        return user;
    }

    @Override
    public Boolean checkPriviledgeOfRecord(Integer recorderId, Integer userId) {
        User recorder = getById(recorderId);
        return recorder != null
                && (recorder.getType().equals(2) || recorder.getAuthScan() != null && recorder.getAuthScan().equals(1));
    }

    @Override
    public void updateUserInfo(Integer userId, Integer cardType, String cardId, String addr, String addrLocal, String phone, String name) {
        lambdaUpdate()
                .eq(User::getId, userId)
                .set(StringUtil.isNotBlank(name), User::getName, name)
                .set(cardType != null, User::getCardType, cardType)
                .set(StringUtil.isNotBlank(cardId), User::getCardId, cardId)
                .set(StringUtil.isNotBlank(addr), User::getAddr, addr)
                .set(StringUtil.isNotBlank(addrLocal), User::getAddrLocal, addrLocal)
                .set(StringUtil.isNotBlank(phone), User::getPhone, phone)
                .update();
    }

    @Override
    public void updTypeArayof(Integer userId) {
        lambdaUpdate()
                .eq(User::getId, userId)
                .set(User::getType, 2)
                .update();
    }

    @Override
    public void updTypeOrdinary(Integer userId) {
        lambdaUpdate()
                .eq(User::getId, userId)
                .set(User::getType, 1)
                .update();
    }

    @Override
    public List<ThisCourtVO> getPage(String name, Integer type, Page page) {
        return userMapper.getPage(name, type, page);
    }

    @Override
    public IPage<PersonInfoVo> getPersonPageList(Integer state, Integer type, String nameOrPhone, String deptName, Integer current, Integer size) {
        String name = null;
        String phone = null;
        if (StringUtil.isNotBlank(nameOrPhone) && StringUtils.isNumeric(nameOrPhone)) {
            phone = nameOrPhone;
        }
        if (StringUtil.isNotBlank(nameOrPhone) && !StringUtils.isNumeric(nameOrPhone)) {
            name = nameOrPhone;
        }
        List<PersonInfoVo> data = userMapper.getPersonPageList(state, type, name, phone, deptName, (current - 1) * size, size);
        int total = userMapper.getPersonPageListSize(state, type, name, phone, deptName);
        IPage<PersonInfoVo> pages = new Page<PersonInfoVo>().setSize(size).setCurrent(current).setRecords(data);
        if (data.isEmpty()) {
            return pages;
        }
        pages.setTotal(total);
        return pages;
    }

    @Override
    public Integer getPageSize(String name, Integer type) {
        return userMapper.getPageSize(name, type);
    }

    @Override
    public void updAuthScan(Integer id, Integer type) {
        lambdaUpdate()
                .eq(User::getId, id)
                .set(User::getType, type)
                .update();
    }

    @Override
    public void updatePersonnel(UpdatePersonnelParam param) throws BizException {
        Assert.isNull(param.getId(), "缺少必要参数");
        User clone = CopyUtil.clone(param, User.class);
        int updateUserSate = userMapper.updateById(clone);
        Assert.isTrue(updateUserSate == 0, "修改用户信息失败");
    }

    @Override
    public void delPersonnel(PersonnelIdParam param) throws BizException {
        Assert.isNull(param.getId(), "缺少必要参数");
        int delUserState = userMapper.delete(Wrappers.<User>lambdaUpdate().eq(User::getId, param.getId()));
        Assert.isTrue(delUserState == 0, "删除用户信息失败");
    }

    @Override
    public void disablePerson(PersonnelIdParam param) throws BizException {
        Assert.isNull(param.getId(), "缺少必要参数");
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId, param.getId()));
        Assert.isNull(user, "该用户不存在");
        if (null != user.getDisable() && user.getDisable() == 0) {
            int updateUserDisable = userMapper.updateById(new User().setId(param.getId()).setDisable(1));
            Assert.isTrue(updateUserDisable == 0, "启用失败,或该用户已经是启用状态");
        } else {
            int updateUserDisable = userMapper.updateById(new User().setId(param.getId()).setDisable(0));
            Assert.isTrue(updateUserDisable == 0, "禁用失败,或该用户已经是禁用状态");
        }
    }

    @Override
    public void powerPerson(PersonnelIdParam param) throws BizException {
        Assert.isNull(param.getId(), "缺少必要参数");
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId, param.getId()));
        Assert.isNull(user, "该用户不存在");
        if (null != user.getAuthScan() && user.getAuthScan() == 0) {
            int updateUserDisable = userMapper.updateById(new User().setId(param.getId()).setAuthScan(1));
            Assert.isTrue(updateUserDisable == 0, "授权失败,或该用户已经被授权");
        } else {
            int updateUserDisable = userMapper.updateById(new User().setId(param.getId()).setAuthScan(0));
            Assert.isTrue(updateUserDisable == 0, "取消授权失败,或该用户已经被取消授权");
        }
    }
}
